const express = require("express");
const router = express.Router();
const { executeQuery } = require("../../mysql");

// POST请求处理创建请假记录
router.post('/leave/create-leave', async (req, res) => {
  const { student_id, date1, date2, leave_type, reason } = req.body;

  // 将日期字符串转换为 MySQL 的日期格式
  const start_date = new Date(date1).toISOString().split('T')[0];
  const end_date = new Date(date2).toISOString().split('T')[0];

  console.log( start_date , end_date );

  // 构建插入数据的 SQL 查询语句
  const insertQuery = `
    INSERT INTO tb_student_leave (student_id, start_date, end_date, leave_type, reason)
    VALUES (?, ?, ?, ?, ?)
  `;
  const values = [student_id, start_date, end_date, leave_type, reason];

  try {
    // 执行 SQL 查询
    const result = await executeQuery(insertQuery, values);

    // 返回成功消息
    res.json({ 
        success: true, 
        leave_id: result.insertId 
    });
  } catch (error) {
    console.error('Error creating leave record:', error);
    res.status(500).json({ error: 'Error creating leave record. Please try again later.' });
  }
});

module.exports = router;